import { toJS } from "mobx";
import { Button,Modal,Rate,Tabs,Spin,Row,Col,Card,Form,Badge,message} from 'antd';
import { WeaRightMenu,WeaTop,WeaTab,WeaErrorPage,WeaTools,WeaNewScroll,WeaSelect,WeaLeftRightLayout,WeaLeftTree,WeaFormItem,WeaSearchGroup,WeaProgress,WeaDialog } from "ecCom";
import { WeaSwitch, WeaTableNew } from "comsMobx";
const WeaTable = WeaTableNew.WeaTable;
import * as Bctt from "../../constants/BaseListConstant";
import WeaCrmTab from "../comp/weaCrmTab";
import Synergy from '../synergy/index';
import ContractRP from './ContractRP';
// import weaCube from 'weaCube';
// const BatchShareDialog = weaCube.common.ShareCom.BatchShareDialog;
// const ExcelLayoutCom = weaCube.common.ExcelLayoutCom;
import * as cct from '../../constants/CommonConstant';
import RiskRP from "./RiskRP";

class CommonLedger extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            "synergyWidth":1
        }
        this.mathSynergyWidth = this.mathSynergyWidth.bind(this);

        window._contractTable = {reload:this.reload}
    }

    reload=()=>{
        const store = this.getStore();
        store.reload();
    }

    mathSynergyWidth(){
        let contract_table_width = ReactDOM.findDOMNode(this.refs.contract_table).scrollWidth;
        let synergyWidth = contract_table_width*0.75;
        this.setState({"synergyWidth":synergyWidth});
    }

    getStore() {

    }

    // render before
    componentWillMount() {
        // window._cubeCard={};
        const componentParams = {...this.props.params,...this.props.location.query};
        this.getStore().componentWillMount(componentParams);
    }

    // render after
    componentDidMount() {
        if(window.weaCube){
            this.doInit(this.props);
        }else{
            eventRegister.loadModule('f_cube', ()=> {
                this.doInit(this.props);
            })
        }

        // this.getStore().componentDidMount();
        // this.mathSynergyWidth();
        // window.addEventListener("resize",this.mathSynergyWidth);
    }
    doInit(props){
        this.getStore().componentDidMount();
        this.mathSynergyWidth();
    }
    // component remove before
    componentWillUnmount() {
        this.getStore().componentWillUnmount();
    }

    componentWillReceiveProps(nextProps) {
        const store = this.getStore();
        const oldType = store.routerParams.page;
        const newType = nextProps.params.page;
        
		// 切换路由或者点击菜单路由刷新组件
        if (newType&&oldType !== newType) {
            store.componentWillUnmount();
            store.componentWillMount(nextProps.params);
            store.componentDidMount();
            return;
        }
        const flag = this.props.hasOwnProperty("location");
        if(flag){
            const keyOld = this.props.location.key;
            const keyNew = nextProps.location.key;
            if(keyOld !== keyNew){
                store.componentWillUnmount();
                if(oldType=="home"){
                    store.componentWillMount({...nextProps.params,...{page:"home"}});
                }else{
                    store.componentWillMount(nextProps.params);
                }
                store.componentDidMount();
                return;
            }
        }

    }

    render() {
        let synergyWidth = this.state.synergyWidth;
        const store = this.getStore();
        const {loading,viewTop,showSearchAd,tableStore,searchKey,synergyParams,rpData,topInfo,shareStore={},commonParams,routerParams,riskRpData,dialog,Card} = store;
        const {isUse,isShow,refId,tabKey,title} = synergyParams;
        let weaTableProps = {};//WeaTable中的属性集
        weaTableProps.comsWeaTableStore = tableStore;
        weaTableProps.hasOrder = true;
        weaTableProps.needScroll = true;
        if (this.reRenderColumns)
            weaTableProps.getColumns = c => this.reRenderColumns(c);
        if (this.onOperatesClick)
            weaTableProps.onOperatesClick = (record,index,operate,flag) => this.onOperatesClick(record,index,operate,flag);
        weaTableProps.ref="contract_table";

        let tableCom = <WeaTable  {...weaTableProps} style={{paddingLeft:'10px',paddingRight:'10px',paddingTop:'5px'}}/> 

        const searchTypes = this.getTabSearchTypes(store);
        let hasBase = false;
        let hasAdvanced = false;
        for (let t in searchTypes) {
            if (searchTypes[t] == Bctt.TAB_SEARCH_TYPE_BASE) {
                hasBase = true;
            }
            if (searchTypes[t] == Bctt.TAB_SEARCH_TYPE_ADVANCED) {
                hasAdvanced = true;
            }
        }
        let tabCom = null;
        let weaTabProps = {};//WeaTab中的属性集
        weaTabProps.buttons = this.getTabButtons(store);
        weaTabProps.searchType = searchTypes;
        let showWeaTab = false;
        if (hasBase) {
            showWeaTab = true;
            weaTabProps.searchsBaseValue = searchKey;
            weaTabProps.onSearch = store.doSearch;
            weaTabProps.onSearchChange = v => store.setSearchKey(v);
        }

        if (hasAdvanced) {
            showWeaTab = true;
            weaTabProps.showSearchAd = showSearchAd;
            weaTabProps.buttonsAd = this.getAdButtons(store);
            weaTabProps.setShowSearchAd = bool => { store.setShowSearchAd(bool) };
            weaTabProps.hideSearchAd = () => store.setShowSearchAd(false);
            weaTabProps.searchsAd = <Form horizontal>{this.getSearchConditionForm(store)}</Form>;
        }
        if (showWeaTab)
            tabCom = <WeaTab {...weaTabProps} />;

        let reportContent = null;
        if(routerParams.page=="risk"){
            reportContent =<RiskRP location={this.props.location} datas={toJS(riskRpData)}/>;
        }else{
            reportContent =<ContractRP datas={toJS(rpData)}/>;
        }
        // const reportContent =<ContractRP datas={[{"desc":100000.0,"bgc":"4794DF","labelName":"收入合同总金额","type":"img"},{"percent":55.55,"desc":0.0,"bgc":"7180B4","labelName":"累计已收","type":"percent"},{"desc":0.0,"bgc":"4DA8A9","labelName":"支出合同总金额","type":"img"},{"percent":0.0,"desc":0.0,"bgc":"EC6B63","labelName":"累计支出","type":"percent"}]}/>;

        let WeaLeftRightLayoutProps = {};
        WeaLeftRightLayoutProps.isNew = true;
        WeaLeftRightLayoutProps.col = 2;
        WeaLeftRightLayoutProps.defaultShowLeft = true;
        WeaLeftRightLayoutProps.leftWidth = 250;
        WeaLeftRightLayoutProps.leftCom = 
            <div style={{ width: '100%', height: '100%' }} >
                <WeaLeftTree datas={toJS(store.contractType)} onSelect={(key,topTabCount,countsType)=>store.doSearch({"typeTreeId":key})}/>
            </div>;
        let WeaLeftRightLayoutCom = null;
        WeaLeftRightLayoutCom =  
            <WeaLeftRightLayout {...WeaLeftRightLayoutProps}> 
                {tabCom}
                {reportContent}
                {/* <WeaNewScroll height={routerParams.page=="risk"?"calc(100% - 282px)":"calc(100% - 128px)"}> */}
                    {tableCom}
                {/* </WeaNewScroll> */}
            </WeaLeftRightLayout>;

        let BatchShareDialog = {};
        let ExcelLayoutCom = {};
        if(window.weaCube){
            BatchShareDialog = weaCube.common.ShareCom.BatchShareDialog;
            ExcelLayoutCom = weaCube.common.ExcelLayoutCom;
        }

        return (
            <div className="wea-crmReport-base" style={{height:"100%"}}>
                <WeaRightMenu datas={store.getRightMenus()}>
                    <WeaTop
                        loading={loading}
                        title={topInfo.titleName}
                        icon={<i className={cct.icon}/>}
                        iconBgcolor={cct.iconBgcolor}
                        showDropIcon={true}
                        dropMenuDatas={store.getRightMenus()}
                        buttons={store.getTopButtons()}
                        buttonSpace={10}
                    >
                    {WeaLeftRightLayoutCom}
                    {this.renderAppend(store)}
                    </WeaTop>
                </WeaRightMenu>
                {(isUse&&<Synergy isUse={isUse} isShow={isShow} refId={refId} title={title} tabKey={tabKey} custom={synergyWidth} otherParams={commonParams}/>)}
                {(window.weaCube&&shareStore.visible&&<BatchShareDialog share={shareStore} params={{customerid:commonParams.customId,modeid:commonParams.modeId}}/>)}
                {(dialog.visible&&<WeaDialog
                    icon = {cct.icon}
                    iconBgcolor={cct.iconBgcolor}
                    onCancel={()=> store.closeDialog()}
                    title={"新建"}
                    visible={dialog.visible}
                    style={{width: 1100, height: 700}}
                    hasScroll
                    buttons={[
                        (<Button type="ghost" onClick={()=>store.closeDialog()}>关闭</Button>)
                    ]}
                >
                   <WeaRightMenu datas={window.weaCube&&Card.isInit&&Card.cardTab&&Card.cardTab.rightMenus&&Card.cardTab.rightMenus.slice()} onClick={window.weaCube&&Card.isInit&&Card.cardTab&&Card.cardTab.rightMenus&&Card.cardTab.rightMenuHandle}>
                        <div className="wea-contract-contractPage">
                            <div className="coms-mode-docker coms-mode-card wea-contract-contractPage-detail"> 
                                <Spin spinning={Card.loading}>{window.weaCube&&Card.isInit ? <ExcelLayoutCom Card={Card} />:<div style={{marginTop:'50%'}}  />}</Spin> 
                            </div>
                        </div>
                    </WeaRightMenu>
                </WeaDialog>)}
            </div>
        )
    }

    // render custom
    renderAppend(store) {
        return [];
    }


    reRenderColumns(columns){
        let that = this;
        const {synergyStore={}} = this.props;
        const synergyTab = this.props.params.page;
        const store = that.getStore();
        columns.forEach(c=>{
            if(c.dataIndex=='name'){
                c.render = function(text, record){
                    return <div onClick={(bool)=>{store.showSynergy(true,record.randomFieldId,synergyTab,text),typeof(synergyStore) !== "undefined"?synergyStore.isShowSynergy(bool):null}}>
                        <a>{text}</a>
                    </div>
                }
            }else if(c.dataIndex=='cons_name'){
                c.render = function(text, record){
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    let valueSpanText = $(valueSpan)[0]?$(valueSpan)[0].text:valueSpan;
                    return <div onClick={(bool)=>{store.showSynergy(true,text,synergyTab,valueSpanText),typeof(synergyStore) !== "undefined"?synergyStore.isShowSynergy(bool):null}}>
                        <a>{valueSpanText}</a>
                    </div>
                }
            }else if(c.dataIndex=='d_userid'){
                c.render = function(text, record){
                    return <Rate count={1} value={text||0} onChange={()=>store.doAttention(text||0,record.randomFieldId)} />
                }
            }else if(c.dataIndex=='cons_count'){
                c.render = function(text, record){
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    return <span style={{float:'right'}} dangerouslySetInnerHTML={{__html: valueSpan}}></span>;
                }
            }else {
                c.render = function(text, record){
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
                }
            }
        })
        return columns;
    }

    getAdButtons(store) {
        const { doSearch, setShowSearchAd, clearAdFields } = store;
        return [
            (<Button type="primary" onClick={() => { doSearch(); setShowSearchAd(false); }}>搜索</Button>),
            (<Button type="ghost" onClick={() => { clearAdFields(); }}>重置</Button>),
            (<Button type="ghost" onClick={() => { setShowSearchAd(false); }}>取消</Button>)
        ];
    }

    getTabButtons(store) {
        let arr = [];
        return arr;
    }

    getTabSearchTypes(store) {
        let arr = [];
        return arr;
    }

    getSearchConditionForm(store) {
        const { searchConditionComponents, searchConditionForm } = store;
        let groups = [];
        if (searchConditionComponents) {
            const { isFormInit } = searchConditionForm;
            const formParams = searchConditionForm.getFormParams();
            isFormInit && toJS(searchConditionComponents).map(c => {
                let items = [];
                c.items.map((fields, index) => {
                    items.push({
                        com: (<WeaFormItem
                            label={`${fields.label}`}
                            labelCol={{ span: `${fields.labelcol}` }}
                            wrapperCol={{ span: `${fields.fieldcol}` }}>
                            <WeaSwitch fieldConfig={fields} form={searchConditionForm} formParams={formParams} onChange={store.searchConditionFieldChange} />
                        </WeaFormItem>),
                        col: 2,
                    })
                });
                groups.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
            });
        }
        return groups;
    }
}

export default CommonLedger;